﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    private BoxCollider2D collider;
    private Rigidbody2D rigidbody;
    private Transform playerTransform;

    private Vector3 targetPostion = new Vector3(0f,0f,0f);
    private Vector3 offset;//player的位置和enemy的位置的差值

    public float smoothing;
    


    void Start()
    {
        collider = GetComponent<BoxCollider2D>();
        rigidbody = GetComponent<Rigidbody2D>();
        targetPostion = transform.position;
        playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
        GameManager.Instance.enemy.Add(this);

        smoothing = 9f;
        
    }

    
    void FixedUpdate()
    {
        rigidbody.MovePosition(Vector3.Lerp(transform.position, targetPostion, smoothing * Time.fixedDeltaTime));
    }

    public void EnemyMove()
    {
        offset = playerTransform.position - transform.position;
        if (offset.magnitude<1.1f)
        {
            //敌人攻击
        }
        else//敌人移动
        {
            float x = 0f, y = 0f;
            if (Mathf.Abs(offset.y)>Mathf.Abs(offset.x))//向y轴移动
            {
                if (offset.y<0)
                {
                    y = -1f;
                }
                else
                {
                    y = 1f;
                }
                
            }
            else //向x轴移动
            {
                if (offset.x < 0)
                {
                    x = -1f;
                }
                else
                {
                    x = 1f;
                }

            }
            collider.enabled = false;
            RaycastHit2D hit = Physics2D.Linecast(transform.position, transform.position + new Vector3(x, y, 0f));
            collider.enabled = true;
            if (hit.transform == null)
            {
                targetPostion += new Vector3(x, y, 0f);
            }
            else
            {
                if (hit.collider.tag == "Soda" || hit.collider.tag == "Food")
                {
                    targetPostion += new Vector3(x, y, 0f);
                }
            }
            

        }
        
        
    }
}
